package com.ddwl.shop.service;

import com.alibaba.fastjson.JSON;
import com.ddwl.common.constant.RedisKey;
import com.ddwl.common.feign.wx.WxBaseApi;
import com.ddwl.common.service.RedisService;
import com.ddwl.schema.util.DateUtil;
import com.ddwl.schema.vo.base.WxRestVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.Map;
import java.util.Set;

/**
 * @author Fu Zhaohui
 * @date 2017/1/3
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WxTokenService {

    private final WxBaseApi wxApi;
    private final RedisService redisService;


    /**
     * 处理微信帐号信息加入到Redis
     */
    public void handleToken() {
        Set<String> keys = redisService.getHashOps().getOperations().keys(RedisKey.WX_ACCOUNT_KEY.getKey("*"));
        keys.forEach(accountKey -> {
            log.info("处理wx_account => {}", accountKey);
            Map<String, String> accountMap = redisService.getHashOps().entries(accountKey);
            String key = RedisKey.WX_TOKEN_KEY.getKey(accountMap.get("appId"));
            WxRestVo resp = wxApi.token(accountMap.get("appId"), accountMap.get("appSecret"), "client_credential");
            log.info("wechat token resp: " + JSON.toJSONString(resp));
            String accessToken = resp.getAccess_token();
            redisService.getHashOps().put(key, "accessToken", accessToken);
            resp = wxApi.ticket(accessToken, "jsapi");
            log.info("wechat ticket resp: " + JSON.toJSONString(resp));
            redisService.getHashOps().put(key, "ticket", resp.getTicket());
            long expireTime = System.currentTimeMillis() + resp.getExpires_in() * 1000;
            redisService.getHashOps().put(key, "expires", Long.toString(expireTime));
            redisService.getHashOps().put(key, "expiresTimestamp", DateUtil.formatDate(Instant.ofEpochMilli(expireTime), DateUtil.DATE_TIME_FORMAT));
        });
    }
}
